'use strict';

const db = uniCloud.database();
const collection = db.collection('food-banner');

exports.main = async (event, context) => {
  const { action, bannerIds, data } = event.data || {};
  
  if (!action) {
    return {
      code: 400,
      message: '操作类型不能为空',
      data: null
    };
  }
  
  if (!bannerIds || !Array.isArray(bannerIds) || bannerIds.length === 0) {
    return {
      code: 400,
      message: '轮播图ID列表不能为空',
      data: null
    };
  }
  
  try {
    let result;
    let message = '';
    
    switch (action) {
      case 'batch-delete':
        // 批量删除
        result = await collection.where({
          _id: db.command.in(bannerIds)
        }).remove();
        
        message = `成功删除 ${result.deleted} 个轮播图`;
        break;
        
      case 'batch-update-status':
        // 批量更新状态
        if (data === undefined || data.status === undefined) {
          return {
            code: 400,
            message: '状态数据不能为空',
            data: null
          };
        }
        
        result = await collection.where({
          _id: db.command.in(bannerIds)
        }).update({
          status: data.status,
          update_date: Date.now()
        });
        
        message = `成功更新 ${result.updated} 个轮播图状态`;
        break;
        
      case 'batch-update-sort':
        // 批量更新排序
        if (data === undefined || data.sort === undefined) {
          return {
            code: 400,
            message: '排序数据不能为空',
            data: null
          };
        }
        
        result = await collection.where({
          _id: db.command.in(bannerIds)
        }).update({
          sort: data.sort,
          update_date: Date.now()
        });
        
        message = `成功更新 ${result.updated} 个轮播图排序`;
        break;
        
      default:
        return {
          code: 400,
          message: '不支持的操作类型',
          data: null
        };
    }
    
    return {
      code: 200,
      message,
      data: result
    };
  } catch (error) {
    console.error('批量操作轮播图失败:', error);
    return {
      code: 500,
      message: '批量操作失败',
      data: null
    };
  }
};